package com.softline.documentsmall.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.softline.documentsmall.dao.ZsIndexDetailMapper;
import com.softline.documentsmall.entity.*;
import com.softline.documentsmall.ret.ReturnVO;
import com.softline.documentsmall.ret.ReturnVOUtils;
import com.softline.documentsmall.service.ZsIndexDetailService;
import com.softline.documentsmall.utils.VoTransferUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhongweicheng
 * @DATE 2021-03-16
 */
@Service
public class ZsIndexDetailServiceImpl implements ZsIndexDetailService {


    @Autowired
    ZsIndexDetailMapper zsIndexDetailMapper;

    /**
     * type:1:全球数字竞争力指数，2.大数据发展指数,3.大数据法治指数,4.大数据安全指数,5.大数据金融风险防控指数,6.治理科技指数
     * year:yyyy
     * 该变量用于修复分指数-列表按照excel顺序展示
     *map key遵循yyyy-type设置，方便获取
     */
    public static   Map<String,String[]> smallIndexOrder = Maps.newHashMap();

    static {
        String[] v1 = new String[]{"数字创新","数字经济","数字治理","数字服务","数字安全"};
        smallIndexOrder.put("1",v1);
        String[] v2 = new String[]{"政用指数","商用指数","民用指数"};
        smallIndexOrder.put("2",v2);
        String[] v3 = new String[]{"数据立法","数字司法","数权保护"};
        smallIndexOrder.put("3",v3);
        String[] v4 = new String[]{"安全制度","安全产业","安全能力","安全生态"};
        smallIndexOrder.put("2020-4",v4);
        String[] v7 = new String[]{"安全制度","安全设施","安全能力","安全生态"};
        smallIndexOrder.put("2019-4",v7);
        String[] v5 = new String[]{"金融稳定","金融风险","金融可持续发展"};
        smallIndexOrder.put("2020-5",v5);
        String[] v8 = new String[]{"金融稳定","金融风控","金融可持续发展"};
        smallIndexOrder.put("2019-5",v8);
        String[] v6 = new String[]{"制度保障","发展环境","支撑能力","场景应用","效能评估"};
        smallIndexOrder.put("6",v6);




    }



    @Override
    public ReturnVO list(String type, String year, String areaType,String languageType) {
       List<ZsIndexDetail> zsIndexDetailList = zsIndexDetailMapper.findByParams(type,year,areaType);
       //如果是大数据发展指数，需要把其余几个小指数的总指数也返回
        if("2".equalsIgnoreCase(type)){
            return ReturnVOUtils.success(bidDataDevDetail(zsIndexDetailList,areaType,year,type,languageType));
        }
       return ReturnVOUtils.success(commonVoDel(zsIndexDetailList,areaType,year,type));
    }

    @Override
    public ReturnVO cityList(String year,String areaType,String type,String languageType) {

        return ReturnVOUtils.success(zsIndexDetailMapper.cityList(year,areaType,type,languageType));
    }

    /**
     * 大数据发展指数页面 type需要1和2的数据
     * @param name
     * @param year
     * @return
     */
    @Override
    public ReturnVO bigDataDevIndexGetIndexDetail(String name, String year,String areaType,String type,String languageType) {
        List<ZsIndexDetail> details = zsIndexDetailMapper.bigDataDevIndexGetIndexDetail(areaType,name,year,type,languageType);
        return ReturnVOUtils.success(commonVoDel(details,areaType,year,type)) ;
    }


    /**
     * 通用转化方法
     * @param zsIndexDetailList
     * @return
     */
    public List<ZsIndexDetailVo> commonVoDel(List<ZsIndexDetail> zsIndexDetailList,String areaType,String year,String type){

        List<ZsIndexDetailVo> vs = Lists.newArrayList();
        if(zsIndexDetailList != null && zsIndexDetailList.size() != 0){
            {
                //分组处理返回数据
                Map<Object,List<ZsIndexDetail>> maps = zsIndexDetailList.stream().collect(Collectors.groupingBy(r->r.getNameCn()));
                maps.forEach((k,v)->{
                    ZsIndexDetailVo vo =  new ZsIndexDetailVo();
                    vo.setAreaType(areaType);
                    vo.setYear(year);
                    vo.setType(type);
                    vo.setNameCn(k.toString());
                    vo.setTotalRank(v.get(0).getTotalRank());
                    vo.setTotalIndex(v.get(0).getTotalIndex());
                    vo.setTotalChangeRank(v.get(0).getTotalChangeRank());
                    vo.setNameEn(v.get(0).getNameEn());
                    Map<String,String> m = Maps.newHashMap();
                    List<ZsIndexDetailVo.DataLabelInfo> infos = Lists.newArrayList();

                    //对v按照指定的小指数顺序处理
                    if(smallIndexOrder != null){
                        String[] order = new String[10];
                        //安全、金融防控特殊处理
                        if("4".equalsIgnoreCase(type)||"5".equalsIgnoreCase(type)){
                         order =  smallIndexOrder.get(year+"-"+type);
                        }else {
                            order = smallIndexOrder.get(type);
                        }
                       if(order != null && order.length !=0){
                           for(String a:order){
                               for(ZsIndexDetail c:v){
                                   //只取有效值
                                   if(c.getDataLabelCn().equalsIgnoreCase(a)){
                                       //封装动态扩展列,中英文都存，便于前端按需展示
                                       ZsIndexDetailVo.DataLabelInfo i = new ZsIndexDetailVo.DataLabelInfo();
                                       i.setDataInfo(c.getDataInfo());
                                       i.setDataLabelEn(c.getDataLabelEn());
                                       i.setDataLabelCn(c.getDataLabelCn());
                                       i.setLabelRank(c.getLabelRank()==null?0:c.getLabelRank());
                                       infos.add(i);
                                       break;
                                   }
                               }
                           }
                        }
                    }

                    vo.setDataLabelInfos(infos);
                    //获取最大值 设置幅度使用
                    if (infos.size() != 0) {
                        List<Double> a  = infos.stream().map(r->{
                            String cc = r.getDataInfo();
                             return Double.parseDouble(cc);
                        }).collect(Collectors.toList());

                        vo.setMaxLabelIndex(Collections.max(a)+"");
                    }
                    //获取指数趋势数据，最新五年
                    Map<String,Object> trends = Maps.newHashMap();
                    List<Integer> years =  VoTransferUtils.getFiveYear();
                    if(years != null && years.size() != 0){
                        //根据年限查询
                        years.stream().forEach(r->{
                            String totalIndex =   zsIndexDetailMapper.findTotalIndexByYear(r.toString(),areaType,type,k.toString());
                            //为了友好，为空就设置为0
                            trends.put(r.toString(),totalIndex ==null?"0":totalIndex);
                        });
                    }
                    vo.setIndexTrends(trends);
                    //全球数字竞争力并且是城市类型时,需要返回经纬度
                    if("1".equalsIgnoreCase(type) &&"3".equalsIgnoreCase(areaType)){
                       Map map =  zsIndexDetailMapper.getCityLocationByName(vo.getNameEn());
                       if(map != null) {
                           vo.setLongitude(map.get("longitude").toString());
                           vo.setLatitude(map.get("latitude").toString());
                       }
                    }
                    vs.add(vo);
                });
            }
        }
        Collections.sort(vs, new Comparator<ZsIndexDetailVo>() {
            public int compare(ZsIndexDetailVo o1, ZsIndexDetailVo o2) {
                return o1.getTotalRank().compareTo(o2.getTotalRank());
            }
        });
        return vs;
    }

   public List<ZsBigDataDevIndexDetailVo> bidDataDevDetail(List<ZsIndexDetail> zsIndexDetailList,String areaType,String year,String type ,String languageType){
       List<ZsBigDataDevIndexDetailVo> vs = Lists.newArrayList();
       if(zsIndexDetailList != null && zsIndexDetailList.size() != 0){
           {
               //分组处理返回数据
               Map<Object,List<ZsIndexDetail>> maps = zsIndexDetailList.stream().collect(Collectors.groupingBy(r->r.getNameCn()));
               maps.forEach((k,v)->{
                   ZsBigDataDevIndexDetailVo vo =  new ZsBigDataDevIndexDetailVo();
                   vo.setAreaType(areaType);
                   vo.setYear(year);
                   vo.setType(type);
                   vo.setNameCn(k.toString());
                   vo.setTotalRank(v.get(0).getTotalRank());
                   vo.setTotalIndex(v.get(0).getTotalIndex());
                   vo.setTotalChangeRank(v.get(0).getTotalChangeRank());
                   vo.setNameEn(v.get(0).getNameEn());
                   Map<String,String> m = Maps.newHashMap();
                   List<ZsBigDataDevIndexDetailVo.DataLabelInfo> infos = Lists.newArrayList();
                   //对v按照指定的小指数顺序处理
                   if(smallIndexOrder != null){
                       String[] order = new String[10];
                       //安全指数特殊处理
                       if("4".equalsIgnoreCase(type)||"5".equalsIgnoreCase(type)){
                           order =  smallIndexOrder.get(year+"-"+type);
                       }else {
                           order = smallIndexOrder.get(type);
                       }
                       if(order != null && order.length !=0){
                           for(String a:order){
                               for(ZsIndexDetail c:v){
                                   //只取有效值
                                   if(c.getDataLabelCn().equalsIgnoreCase(a)){
                                       //封装动态扩展列,中英文都存，便于前端按需展示
                                       ZsBigDataDevIndexDetailVo.DataLabelInfo i = new ZsBigDataDevIndexDetailVo.DataLabelInfo();
                                       i.setDataInfo(c.getDataInfo());
                                       i.setDataLabelEn(c.getDataLabelEn());
                                       i.setDataLabelCn(c.getDataLabelCn());
                                       i.setLabelRank(c.getLabelRank()==null?0:c.getLabelRank());
                                       infos.add(i);
                                       break;
                                   }
                               }
                           }
                       }
                   }
                   vo.setDataLabelInfos(infos);
                   //获取最大值 设置幅度使用
                   if (infos.size() != 0) {
                       List<Double> a  = infos.stream().map(r->{
                           String cc = r.getDataInfo();
                           return Double.parseDouble(cc);
                       }).collect(Collectors.toList());

                       vo.setMaxLabelIndex(Collections.max(a)+"");
                   }
                   //获取指数趋势数据，最新五年
                   Map<String,Object> trends = Maps.newHashMap();
                   List<Integer> years =  VoTransferUtils.getFiveYear();
                   if(years != null && years.size() != 0){
                       //根据年限查询
                       years.stream().forEach(r->{
                           String totalIndex =   zsIndexDetailMapper.findTotalIndexByYear(r.toString(),areaType,type,k.toString());
                           //为了友好，为空就设置为0
                           trends.put(r.toString(),totalIndex ==null?"0":totalIndex);
                       });
                   }
                   vo.setIndexTrends(trends);
                   //其余指数总得分封装
                   Map<String,String> other = Maps.newHashMap();
                   for(int i = 3;i<=6;i++){
                       String value = zsIndexDetailMapper.findOtherIndexByType(year,k.toString(),i+"");
                       String a = zsIndexDetailMapper.findNameByType(i+"",languageType);
                       //获取大指数,根据类型
                       other.put(a,value==null?"0":value);
                   }
                   vo.setOtherTotalIndex(other);
                   vs.add(vo);
               });
           }
       }

       Collections.sort(vs, new Comparator<ZsBigDataDevIndexDetailVo>() {
           public int compare(ZsBigDataDevIndexDetailVo o1, ZsBigDataDevIndexDetailVo o2) {
               return o1.getTotalRank().compareTo(o2.getTotalRank());
           }
       });
       return vs;
   }

    /**
     * 国内城市详情页
     * @param type
     * @param languageType
     * @param name
     * @param year
     * @param areaType1
     * @return
     */
  public ReturnVO innerCountryDetail(String type,String languageType,String name,String year,String areaType1){
     String  areaType = cityTrans(name,areaType1,type,languageType,year);
     List<ZsIndexDetail> details =  zsIndexDetailMapper.innerCountryDetail(type,languageType,name,year,areaType);
      ZsIndexInnerCountryVo vo =  new ZsIndexInnerCountryVo();
     if(details != null && details.size() != 0){
         {
             vo.setAreaType(areaType);
             vo.setYear(year);
             vo.setType(type);
             vo.setNameCn(details.get(0).getNameCn());
             vo.setTotalRank(details.get(0).getTotalRank());
             vo.setTotalIndex(details.get(0).getTotalIndex());
             vo.setNameEn(details.get(0).getNameEn());
             Map<String,List<ZsInnerCountryHistogramVo>> m = Maps.newLinkedHashMap();
             List<ZsIndexInnerCountryVo.DataLabelInfo> infos = Lists.newArrayList();

             //对v按照指定的小指数顺序处理
             if(smallIndexOrder != null){
                 String[] order = new String[10];
                 //安全指数特殊处理
                 if("4".equalsIgnoreCase(type)||"5".equalsIgnoreCase(type)){
                     order =  smallIndexOrder.get(year+"-"+type);
                 }else {
                     order = smallIndexOrder.get(type);
                 }
                 if(order != null && order.length !=0){
                     for(String a:order){
                         for(ZsIndexDetail c:details){
                             //只取有效值
                             if(c.getDataLabelCn().equalsIgnoreCase(a)){
                                 //封装动态扩展列,中英文都存，便于前端按需展示
                                 ZsIndexInnerCountryVo.DataLabelInfo i = new ZsIndexInnerCountryVo.DataLabelInfo();
                                 i.setDataInfo(c.getDataInfo());
                                 i.setDataLabelEn(c.getDataLabelEn());
                                 i.setDataLabelCn(c.getDataLabelCn());
                                 i.setLabelRank(c.getLabelRank()==null?0:c.getLabelRank());
                                 infos.add(i);
                                 break;
                             }
                         }
                     }
                 }
             }
             vo.setDataLabelInfos(infos);
             //获取最大值 设置幅度使用
             if (infos.size() != 0) {
                 List<Double> a  = infos.stream().map(r->{
                     String cc = r.getDataInfo();
                     return Double.parseDouble(cc);
                 }).collect(Collectors.toList());
                 vo.setMaxLabelIndex(Collections.max(a)+"");
             }

             //全球数字竞争力并且是城市类型时,需要返回经纬度
             if("1".equalsIgnoreCase(type) &&"3".equalsIgnoreCase(areaType)){
                 Map map =  zsIndexDetailMapper.getCityLocationByName(vo.getNameEn());
                 if(map != null) {
                     vo.setLongitude(map.get("longitude").toString());
                     vo.setLatitude(map.get("latitude").toString());
                 }
             }

             //国内城市下方柱状图,按照排名
             //按照总指数降序排序
             List<ZsInnerCountryHistogramVo> v1 = zsIndexDetailMapper.BigHistogram(type,year,areaType);
             //根据typ，获取大指数的名称
             String bigName = zsIndexDetailMapper.findNameByType(type,languageType);
             m.put(bigName,v1);
             //各个小指数排名
             if(infos.size() != 0){
                 infos.stream().forEach(r->{
                     String labelName =  r.getDataLabelEn();
                     String key = "";
                     if("en".equalsIgnoreCase(languageType)){
                         key = r.getDataLabelEn();
                     }else{
                         key = r.getDataLabelCn();
                     }
                    m.put( key,zsIndexDetailMapper.smallHistogram(type,year,areaType,labelName));
                 });
             }
             vo.setCountryRank(m);
         }
     }
        return ReturnVOUtils.success(vo);
   }

   String cityTrans(String name,String areaType,String type,String languageType,String year){
      areaType = zsIndexDetailMapper.getAreaTypeCityDetail(type,languageType,name,year);
       return areaType;
   }

    /**
     * 数据比较初始化接口，先展示三条数据，贵阳优先展示
     * @param type
     * @param languageType
     * @param year
     * @param areaType
     * @return
     */
    @Override
    public ReturnVO dataCompareInit(String type, String languageType, String year, String areaType) {
        //获取城市列表
         ReturnVO c = cityList(year, areaType, type, languageType);
         List<ZsIndexDetailVo> vs = Lists.newArrayList();
        List<String> citys = (List<String>) ((ReturnVO)c.getData()).getData();
        if(citys != null && citys.size() != 0){
            int count = 0;
            //先看看有没有贵阳 Guizhou
           Long d = citys.stream().filter(r->r.contains("贵阳")||r.contains("Guiyang")).count();
            Long a = citys.stream().filter(r->r.contains("贵州")||r.contains("Guizhou")).count();

           if(d != 0L || a != 0L){
               if(d != 0L) {
                   //说明有贵阳，取一条贵阳的数据，调用查询接口
                   List<ZsIndexDetailVo> v = (List<ZsIndexDetailVo>) ((ReturnVO) bigDataDevIndexGetIndexDetail("贵阳", year, areaType, type, "cn").getData()).getData();
                   vs.add(v.get(0));
               }else if(a != 0L){
                   //说明有贵州，取一条贵州的数据，调用查询接口
                   List<ZsIndexDetailVo> v = (List<ZsIndexDetailVo>) ((ReturnVO) bigDataDevIndexGetIndexDetail("贵州", year, areaType, type, "cn").getData()).getData();
                   vs.add(v.get(0));
               }

              //再随便找两个除了贵阳之外的
               for(String a1:citys){
                   if(count ==2){
                       break;
                   }
                   if(a1.contains("贵阳")||a1.contains("Guiyang")||a1.contains("贵州")||a1.contains("Guizhou")){
                       continue;
                   }else{
                      vs.add (((List<ZsIndexDetailVo>)((ReturnVO)bigDataDevIndexGetIndexDetail(a1, year,areaType,type,languageType).getData()).getData()).get(0));
                       count++;
                   }
               }

           }else{
               //随便取三个
               for(String a1:citys){
                   if(count ==3){
                       break;
                   }
                   vs.add (((List<ZsIndexDetailVo>)((ReturnVO)bigDataDevIndexGetIndexDetail(a1, year,areaType,type,languageType).getData()).getData()).get(0));
                   count++;
               }
           }
           //对vs按照总指数排个序
            Collections.sort(vs, new Comparator<ZsIndexDetailVo>() {
                public int compare(ZsIndexDetailVo o1, ZsIndexDetailVo o2) {
                    return o1.getTotalRank().compareTo(o2.getTotalRank());
                }
            });

        }

        return ReturnVOUtils.success(vs);
    }
}
